package com.sq.partner.manager.sso.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.jasig.cas.client.authentication.AttributePrincipal;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.controller.LoginController;
import com.sq.partner.manager.mybatis.model.DeptDto;
import com.sq.partner.manager.mybatis.model.GatewayMenuUri;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.IGatewayMenuUriService;
import com.sq.partner.manager.service.IGatewayRoleDeptService;
import com.sq.partner.manager.service.IGatewayUserLoginService;
import com.sq.partner.manager.service.IGatewayUserService;
import com.sq.partner.manager.util.ApplicationContextUtil;
import com.sq.partner.manager.util.LogUtil;

/**
 * SSO登陆信息转化为本地信息
 */
public class SSOUserAdapterFilter implements Filter {
	private static Logger logger = LogUtil.getLog(SSOUserAdapterFilter.class);

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		HttpSession session = req.getSession();
		Object userObj = session.getAttribute(Constants.SESSION_USER);
		boolean hasUser = false;
		if(userObj != null && userObj instanceof GatewayUser){
			GatewayUser user = (GatewayUser)userObj;
			if(user.getSwitchValue().equals(Constants.SWITCH_VALUE_SSO)){
				String userName = user.getUserName();
				hasUser = true;
				logger.debug("登陆用户:"+userName);
			}
		}
		
		if(!hasUser){
			AttributePrincipal principal = (AttributePrincipal) req.getUserPrincipal();
			String userId = principal.getName();
			//加载用户信息
			//单点登陆已成功，补全用户信息 此请求是在SSOAdapterFilter中转发过来的
			try{
				IGatewayUserLoginService iGatewayUserLoginService = (IGatewayUserLoginService)ApplicationContextUtil.getBean("gatewayUserLoginServiceImpl");
				GatewayUser gatewayuser = iGatewayUserLoginService.queryUser(userId);
				if(gatewayuser == null){
					String msg = "该用户在本系统不存在，请配置用户信息";
					req.setAttribute("javax.servlet.error.message",msg);
		        	req.setAttribute("url",req.getRequestURI());
		            req.getRequestDispatcher("/common/error").forward(req, res);
				}else{
					if(gatewayuser.getStatus()==2){
						String msg = "该用户在本系统已失效，请配置用户信息";
						req.setAttribute("javax.servlet.error.message",msg);
			        	req.setAttribute("url",req.getRequestURI());
			            req.getRequestDispatcher("/common/error").forward(req, res);
					}else{
						//补充权限、菜单信息
						addDeptMenuInfo(gatewayuser);
						//设置登陆方式
						gatewayuser.setSwitchValue(Constants.SWITCH_VALUE_SSO);
						session.setAttribute(Constants.SESSION_USER,gatewayuser);
						logger.info("用户:[" + gatewayuser.getUserName()+"]登陆成功,登陆方式" + Constants.SWITCH_VALUE_SSO);
						//登录成功，更新该用户最后一次登录时间
						gatewayuser.setLastLogintime(new Date());
						IGatewayUserService userSerive = (IGatewayUserService)ApplicationContextUtil.getBean("gatewayUserServiceImpl");
						userSerive.saveUser(gatewayuser);
						chain.doFilter(request, response);
					}
				}
			}catch(Exception e){
				logger.info(e);
				throw new ServletException(e);
			}
			
		}else{
			chain.doFilter(request, response);
		}
		
	}
	private void addDeptMenuInfo(GatewayUser user) throws Exception{
		//给user对象的权限机构list赋值
		IGatewayRoleDeptService roledeptService = (IGatewayRoleDeptService)ApplicationContextUtil.getBean("gatewayRoleDeptServiceImpl");
		List<DeptDto> list = roledeptService.queryDeptDto(user.getUserid());
		if(null!=list && list.size() >0){
			user.setDepartmentStr(LoginController.deptStr(list));
			user.setDepts(list);
		}
		
		//给user对象的菜单list赋值
		IGatewayMenuUriService menuUriService = (IGatewayMenuUriService)ApplicationContextUtil.getBean("gatewayMenuUriServiceImpl");
		List<GatewayMenuUri> menuuriList = menuUriService.queryLoginUserMenuUri(user.getUserid());
		List<String> urilist = new ArrayList<String>();
		if(null!=menuuriList && menuuriList.size()>0){
			for(int i=0;i<menuuriList.size();i++){
				urilist.add(menuuriList.get(i).getUri());
			}
			user.setUriList(urilist);
		}
	}
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}
}
